const {Router} = require('express')
const router = new Router()

const path = require('path')

// 引入userImformation模型
const userImformationModel = require('../model/userImformation')
// 引入移动文件函数
const moveFile = require('../utils/fileUtils/moveFile')
// 引入url
const url = require('../config/url')

router.post('/register',function (request, response) {
    const time = new Date()
    const {email, nickname, password} = request.body
    let {imgUrl} = request.body
    const count = time.getTime()

    const data = {
        code: '200',
        msg: 'error',
        data: '注册失败'
    }
    userImformationModel.findOne({
        email
    },(err, doc)=>{
        if (err) return response.json(data)
        else {
            if(doc){
                data.data = '邮箱已被注册！'
                return response.json(data)
            }else {
                // 需要移动的文件名
                const fileName = path.parse(imgUrl).base
                // 需要移动到的文件路径
                const newPath = path.resolve(__dirname,'../public/free/userPic',fileName)
                // 旧文件路径
                const oldPath = path.resolve(__dirname,'../public/free/temp',fileName)

                moveFile(newPath,oldPath, status =>{
                    if (!status.isSuccess) return response.json(data)

                    imgUrl =  `${url}public/free/userPic/${fileName}`

                    userImformationModel.create({
                        imgUrl,
                        nickname,
                        password,
                        count,
                        email,
                        roles: ['admin']
                    },(err, doc)=>{
                        if (err) return response.json(data);
                        else {
                            data.data = doc
                            data.msg = 'success'
                            return response.json(data)
                        }
                    })
                })


            }
        }
    })

})

// 导出
module.exports = router
